package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private ITravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public TravelComment save(TravelComment comment) {
        if (!StringUtils.hasLength(comment.getId())) {
            comment.setCreateTime(new Date());
        }

        //处理引用评论
        String refId = comment.getRefComment().getId();
        if(StringUtils.hasLength(refId)) {
            //评论的评论
            TravelComment ref = repository.findById(refId).get();
            comment.setRefComment(ref);
        }
        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        //repository和template无法直接查询分页数据, 所以需要自己封装
        Query query = new Query();
        //拼接查询条件
        if (qo.getTravelId() != -1) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        //查总数
        long count = template.count(query, TravelComment.class);
        if (count == 0) {
            return Page.empty();
        }
        //查询当前页的list
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "createTime");
        List<TravelComment> list = template.find(query, TravelComment.class);
        return new PageImpl(list, pageable, count);
    }

    @Override
    public Long getCount(Long travelId) {
        Query query = new Query();
        if (travelId != null){
            query.addCriteria(Criteria.where("travelId").is(travelId));
        }
        //查询总数
        long count = template.count(query, TravelComment.class);
        return count;
    }

    @Override
    public List<TravelComment> selectByUserId(Long id) {
        return repository.findByUserId(id);
    }

}
